package com.sto.stoapp.activity.scanner;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;
public class StoScanHandoverActivity extends StoListenerActivity {

    private StoHhmEditText nextDept;
    // private StoHhmEditText code;

    private DataBusinessEntity dataBusiness;
    
    private final int COURIER_RESULT = 0xfe;
    // private int count = 0;

    private String busiType = HomeBroadAction.SCANNER_MAN_BROAD;

    private String nextDeptCode = "", nextDeptName = "";
    
    private List<EditText> edit = new ArrayList<EditText>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sto_scanning_handover);
        Bundle extras = getIntent().getExtras();
        busiType = extras.getString("busiType");
        this.setTitleBottom(R.string.handover_scan, busiType);

        dataBusiness = new DataBusinessEntity();
        dataBusiness.initInsertData();
        initPointLayout(true);
        initWidget();
        initListen();
        initScanListener();
        if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
            initScanRecordAdapter(EnumTableNames.STATUS_TABLE_JOIN_SCAN);
        } 
    }

    /*
     * 初始化控件
     */
    private void initWidget() {
        nextDept = (StoHhmEditText) this
                .findViewById(R.id.sanning_next_dept_person);
        code = (StoHhmEditText) this.findViewById(R.id.sanning_code);
        edit.add(nextDept);
        edit.add(code);
        if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
            addUploadTable(EnumTableNames.STATUS_TABLE_JOIN_SCAN);
        }
    }

    /**
     * 选择列表返回的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == COURIER_RESULT && resultCode == RESULT_OK) {
            GetTableParcel courierEntity = data.getParcelableExtra("Name");
            if (courierEntity != null) {
                nextDept.setText(courierEntity.getSelectName());
                nextDept.setSelection(nextDept.length());
                nextDeptCode = courierEntity.getSelectCode();

                if (nextDeptCode.length() > 0)
                    nextDeptName = courierEntity.getSelectName();
                code.requestFocus();
            }
        } else if (requestCode == COURIER_RESULT
                && resultCode == RESULT_FIRST_USER) {
            nextDept.setText("");
            nextDeptName = "";
            Helper.showSoundToast(this,
                    getString(R.string.undefined), false);
        }
    }

    // 处理扫描数据
    @SuppressLint("NewApi")
    private void processScanData() {
        try {
            if (nextDeptCode.isEmpty()) {
                Helper.showSoundToast(this, "下级部门不能为空", false);
                nextDept.requestFocus();
                return;
            }
            if (!nextDeptName.equals(nextDept.getText().toString())) {
                Helper.showSoundToast(this, "请选择正确的下级部门", false);
                nextDept.requestFocus();
                nextDept.setText("");
                return;
            }
            if (!nextDeptCode.isEmpty() && !code.getText().toString().isEmpty()) {

                //Add by wj过滤单号
                boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
                if(isFilter){
                    showFilterDialog(code.getText().toString().trim());
                    return;
                }
                //End by wj

                if (addPieceRecord()) {
                    this.addCodeNumber();
                    setSaveData(true);
                    // SoundManager.getInstance(this).playSuccessSound();
                    Helper.showSoundAndVibrator(this, true);
                    code.setSelection(code.length());
                    addScanRecordInfo(code.getText().toString());
                    code.setText("");
                }
                // 提示插入数据失败
                else {
                    Helper.showSoundToast(this,
                            getString(R.string.code_repeat), false);
                }
                ScanOpen();
            }
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionLog.writeLog("processScanData", e.getMessage());
        }
    }

    // 增加一条记录
    private boolean addPieceRecord() {
        boolean ret = false;
    
        // 单号
        dataBusiness.setBar_code_number(code.getText().toString());

        dataBusiness.setCodeType(getExpType(code.getText().toString()));
        // 下级部门
        dataBusiness.setNext_station(nextDeptCode);
        // 下级部门名称
        dataBusiness.setUser_defined3(nextDept.getText().toString());
        // 网点编号
        dataBusiness.setNet_code(StoFilePreference.getInstance(this)
                .getSiteCode());
        // 工号
        dataBusiness.setJob_number(StoFilePreference.getInstance(this)
                .getUserCode());
        // 插入数据
        if (busiType.equals(HomeBroadAction.SCANNER_MAN_BROAD)) {
            // 扫描类型
            dataBusiness
                    .setCommand_type(EnumTableNames.STATUS_TABLE_JOIN_SCAN
                            .getOpCode());
            ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
                    EnumTableNames.STATUS_TABLE_JOIN_SCAN);
        } 
        return ret;
    }

    /*
     * 下级部门
     */
    private void selectNextDept() {
        try {
            SelectTableParcel tableParcel = new SelectTableParcel();
            if (nextDept.getText().length() == 0) {
                tableParcel.setSelectSql(SqlSelectTableManager.SQL_NETSITE_NEXT_DEPT_ALL);
                tableParcel.setSelectField(new String[] {});
            } else {
                tableParcel
                        .setSelectSql(SqlSelectTableManager.SQL_NETSITE_NEXT_DEPT_ONLY_LIKE);
                tableParcel.setSelectField(new String[] {
                		"%"+nextDept.getText().toString() + "%",
                		"%"+nextDept.getText().toString() + "%" });
            }
            tableParcel.setSelectCode(SITE_CODE_NUMBER);
            tableParcel.setSelectName(SITE_CODE_NAME);
            tableParcel.setProperty(null);

            Intent intent = new Intent(this,
                    StoSelectTableActivity.class);
            intent.putExtra("tableData", tableParcel);

            startActivityForResult(intent, COURIER_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionLog.writeLog("selectNextDept", e.getMessage());
        }
    }

    /*
     * 监听控件
     */
    @SuppressLint("NewApi")
    private void initListen() {

        nextDept.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {
                onBackPressed();
            }

            @Override
            public void onEditClickListener(View v) {
//                selectNextDept();
            }
        });

        findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectNextDept();
            }
        });
        code.setEditDelete(new EditClickListener() {

            @Override
            public void onEditDelete() {
                nextDept.requestFocus();
                // stayPerson.setSelection(stayPerson.getText().toString()
                // .length());
            }

            @Override
            public void onEditClickListener(View v) {
                codeProcess();

            }
        });



        for (EditText editListener : edit) {
            /*
             * 监听EditText内容个数
             */
            editListener.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    // 控件没有内容就清空编号
                    if (nextDept.getText().toString().isEmpty()) {
                        nextDeptCode = "";
                        nextDeptName = "";
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
    }

    /**
     * 单号逻辑处理判断
     * 
     * @author wxf
     * 
     */
    private void codeProcess() {
        String codeName = code.getText().toString();

        GetTableParcel data;
        if (codeName.length() == 0) {
            Helper.showSoundToast(this, getString(R.string.code_empty), false);
        } else {
            if (codeName.length() == NEXT_STATION_LENGTH) {
                data = queryNextDept(codeName);
                if (data != null) {
                    nextDept.setText(data.getSelectName());
                    nextDeptCode = data.getSelectCode();
                    nextDeptName = data.getSelectName();
                } else {
                    nextDeptName = "";
                    Helper.showSoundToast(this, getString(R.string.undefined),
                            false);
                }
                code.setText("");

            } else {
                onScanResults(codeName);
                /*
                 * if (CheckScanCode(code.getText().toString())) {
                 * onScanResults(code.getText().toString()); } else {
                 * code.setText(""); }
                 */
            }
        }
    }

    @Override
    public void onBackPressed() {
        // 确定退出吗?
        showNotice();
        // super.onBackPressed();

    }

    @Override
    protected void handlerScanData(String scanData) {

        if (scanData != null && !scanData.equals("")) {
            String result = scanData.toString();
            // 下级部门编号
            if (result.length() == NEXT_STATION_LENGTH) {
                nextDept.setText(result);
                selectNextDept();
            } 
            else {
                EnumScanCode status = ProcessScanCode.getInstance(this)
                        .ScanCodeResolve(result, null);// TABLE_NAME_STATUS.STATUS_TABLE_STAY_WAREHOURSE
                code.setText("");
                code.setText(result);
                code.setSelection(code.length());
                switch (status) {
                // 条码空
                case CODE_EMPTY:
                    // Helper.showSoundToast(
                    // StoScanStayWarehourseActivity.this,
                    // getString(R.string.code_empty), false);
                    break;

                // 非法条码
                case CODE_ILLEGAL:
                    Helper.showSoundToast(this,
                            getString(R.string.error_code), false);
                    break;
                // 成功条码
                case CODE_WAY_BILL:
                    processScanData();
                    break;
                default:
                    break;
                }
                code.setText("");
            }

        } else {
            // SoundManager.getInstance(StoScanStayWarehourseActivity.this)
            // .playFailureSound();
            // Helper.showToast(StoScanStayWarehourseActivity.this,
            // "单号不能为空!");
        }

    }

}
